import pandas as pd
import numpy as np

# 定义流量预测结果
traffic_predict = [2, 3, 4, 5, 6, 7, 5, 4, 3, 1, 8, 2]
# 定义每个基站的服务容量为2，当前有两个基站进行正常服务
FN_SIZE = 2
FN_NUM = 2

'''
能源最小化策略
当前正常工作的服务器->当前服务器服务能力（能力阈值）->监控服务器负载率
所预测的流量超过能力阈值->增加服务器数量以满足流量->调高能力阈值->监控服务器负载率
流量峰值过去，大幅下降->服务器负载率大幅下降->部分服务器转休眠。
traffic_predict = [2, 3, 4, 5, 6, 7, 5, 4, 3, 1, 8, 2]
         FN_NUM = [2, 2, 2, 3, 3, 4, 4, 4, 3, 1, 4, 2]
         FN_CAB = [4, 4, 4, 6, 6, 8, 8, 8, 6, 2, 8, 4]
丢包率             [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
'''


class HistoryLog(object):
    def __init__(self):
        self.FN_nums = []
        self.Energes = []
        self.traffics = []
        self.capability = []
        self.loads = []

    def log(self, FN_num, cab, traffic, load):
        self.FN_nums.append(FN_num)
        self.Energes.append(FN_num * 20)
        self.capability.append(cab)
        self.traffics.append(traffic)
        self.log_load(load)

    def log_load(self, load):
        self.loads.append(load)

    def save(self):
        history = {
            'FN_nums': self.FN_nums,
            'Energes': self.Energes,
            'traffic': self.traffics,
            'capability': self.capability,
            'Packet loss rate': np.sum(np.array(self.traffics) > np.array(self.capability)) / len(self.traffics),
            'load rate': self.loads
        }
        df = pd.DataFrame.from_dict(history)
        df.to_csv('run/log.csv', encoding='utf-8', index=False)


hist = HistoryLog()

for traffc_t in traffic_predict:
    current_ability = FN_SIZE * FN_NUM
    current_load = traffc_t / current_ability
    while current_ability < traffc_t:
        print(f"超出负载上限，traffic:{traffc_t} > ability:{current_ability}, 当前FN数量：{FN_NUM}")
        FN_NUM += 1
        current_ability = FN_SIZE * FN_NUM
        current_load = traffc_t / current_ability

    while current_load < 0.5:
        print(f"负载率太低，current_load:{current_load}, 当前FN数量：{FN_NUM}")
        FN_NUM -= 1
        current_ability = FN_SIZE * FN_NUM
        current_load = traffc_t / current_ability
    hist.log(FN_NUM, current_ability, traffc_t, current_load)
    print(f"------------当前服务器负载率:{current_load}, 当前FN数量：{FN_NUM}----------------")

hist.save()
